package com.xxg.fileshand.activity

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import com.rscja.deviceapi.entity.UHFTAGInfo
import com.xxg.fileshand.R
import com.xxg.fileshand.app.SetInfo
import com.xxg.fileshand.base.BaseVMActivity
import com.xxg.fileshand.base.NoViewModel
import com.xxg.fileshand.base.ext.clickWithTrigger
import com.xxg.fileshand.base.ext.dataConvert
import com.xxg.fileshand.base.ext.getApiService
import com.xxg.fileshand.base.launch
import com.xxg.fileshand.bean.RequestTagBean
import com.xxg.fileshand.constant.Constant
import com.xxg.fileshand.databinding.ActivityFilesInOutBinding
import com.xxg.fileshand.greendao.CaseCodeDTO
import com.xxg.fileshand.greendao.GreenDaoManager
import com.xxg.fileshand.greendao.OfflineRequestDTO
import com.xxg.fileshand.pop.PopBorrowOrReturn
import com.xxg.fileshand.reader.ReaderUtils
import com.xxg.fileshand.type.OperateType
import java.util.UUID

class FilesInOutActivity : BaseVMActivity<ActivityFilesInOutBinding, NoViewModel>() {

    var operateType: OperateType? = null

    var caseCode: String = ""

    var caseInfo: CaseCodeDTO? = null

    var readerName: String? = null
    var readerId: String? = null

    var reason: String = ""

    var isReverseRead = false

    override fun onCreate(savedInstanceState: Bundle?) {
        operateType = intent.getSerializableExtra("operateType") as OperateType?
        if (operateType == null) {
            toast("操作类型为空")
            finish()
            return
        }
        super.onCreate(savedInstanceState)
        showRightText("重读")
        initFilesAdapter()
        initAdapterClick()
        filesAdapter.setOperateType(operateType!!)
        initViews()
        if (operateType?.type == OperateType.OPERATE_TYPE_GUIDE.type
            || operateType?.type == OperateType.OPERATE_TYPE_BORROW.type || operateType?.type == OperateType.OPERATE_TYPE_RETURN.type
            || operateType?.type == OperateType.OPERATE_TYPE_TAKE.type
        ) {
            switchScan(false)
        } else {
            switchScan(true)
        }

        if (operateType?.type == OperateType.OPERATE_TYPE_BORROW.type) { //|| operateType?.type == OperateType.OPERATE_TYPE_RETURN.type
            XPopup.Builder(this@FilesInOutActivity)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .borderRadius(resources.getDimension(R.dimen.dp_10))
                .asCustom(
                    PopBorrowOrReturn(
                        mContext,
                        operateType?.type!!,
                        object : PopBorrowOrReturn.OnConfirmListener {
                            override fun onConfirm(
                                readId: String,
                                readName: String,
                                reason1: String
                            ) {
                                runOnUiThread {
                                    mBinding.tvCaseNumCn.text =
                                        (if (operateType?.type == OperateType.OPERATE_TYPE_BORROW.type) "借阅人：" else "归还人：") + readName
                                    reason = reason1
                                    readerId = readId
                                    readerName = readName
                                }
                            }
                        })
                ).show()
        }

    }

    private fun initViews() {
        mBinding.etCaseCode.setOnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftKeyboard()
                val caseCode = textView.text.toString()
                searchCase(caseCode, true)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

        mBinding.tvInout.clickWithTrigger {
            if (filesList.size == 0) {
                toast("请先读取档案")
                return@clickWithTrigger
            }
            var needPopConfirm = false
            var wzTid = ""
            filesList.forEach {
                wzTid += it.eid + "|"
                if (!needPopConfirm && it.caseCodeTrans.startsWith("错架")) {
                    needPopConfirm = true
                }
            }
            if (wzTid.isNotEmpty()) {
                wzTid = wzTid.subSequence(0, wzTid.length - 1) as String
            }
            if (operateType?.type == OperateType.OPERATE_TYPE_PUT.type) {
                if (needPopConfirm && !SetInfo.isIgnoreWrongCase()) {
                    XPopup.Builder(this@FilesInOutActivity)
                        .asConfirm(null, "存在错架档案，是否继续") {
                            upWz(wzTid)
                        }.show()
                } else {
                    upWz(wzTid)
                }
            } else if (operateType?.type == OperateType.OPERATE_TYPE_TAKE.type) {
                downWz(wzTid)
            } else if (operateType?.type == OperateType.OPERATE_TYPE_BORROW.type) {
                borrowWz(wzTid)
            } else if (operateType?.type == OperateType.OPERATE_TYPE_RETURN.type) {
                returnWz(wzTid)
            } else if (operateType?.type == OperateType.OPERATE_TYPE_REVERSE.type) {
                reverseWz(wzTid)
            }
        }

//        mBinding.tvRfid.clickWithTrigger {
//            if (ReaderUtils.instance.isScanningRFID.value == true) {
//                toast("请先停止扫描")
//                return@clickWithTrigger
//            }
//            if (isScanTMCode) {
//                XPopup.Builder(this@FilesInOutActivity)
//                    .asConfirm(null, "是否切换为RFID模式") {
//                        isScanTMCode = false
//                        it.text = "RFID模式"
//                    }.show()
//            } else {
//                XPopup.Builder(this@FilesInOutActivity)
//                    .asConfirm(null, "是否切换为扫码模式") {
//                        isScanTMCode = true
//                        it.text = "扫码模式"
//                    }.show()
//            }
//        }

        mBinding.tvReverse.clickWithTrigger {
            switchCaseReverse()
        }

    }

    //倒架
    private fun reverseWz(wzTid: String) {
        val requestTagBeans = mutableListOf<RequestTagBean>()
        wzTid.split("|").forEach {
            requestTagBeans.add(RequestTagBean(it))
        }
        if (SetInfo.isOffline()) {
            val offlineRequestDTO = OfflineRequestDTO()
            offlineRequestDTO.requestType = Constant.REQUEST_REVERSE_WZ
            offlineRequestDTO.requestJson = mapOf(
                "reqId" to UUID.randomUUID().toString(),
                "deviceId" to DeviceUtils.getUniqueDeviceId(),
                "archiveInfos" to Gson().toJson(requestTagBeans),
                "caseCode" to caseInfo!!.caseCode,
            ).toString()
            offlineRequestDTO.requestTime = System.currentTimeMillis()
            GreenDaoManager.addOfflineRequestDTO(offlineRequestDTO)
            toast("倒架成功")
            LogUtils.e("离线倒架成功")
            onBackPressed()
        } else {
            launch({
                val rp = getApiService().moveSaveInfo(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        "archiveInfos" to requestTagBeans,
                        "caseCode" to caseInfo!!.caseCode,
//                        "fromCaseCode" to "",
                    )
                ).dataConvert()
//                toast(rp.remark)
                if (rp.result > 0) {
                    toast("倒架成功")
                    onBackPressed()
                } else {
                    toast(rp.msg)
                }
            }, {
                toast(it.message)
            })
        }
    }

    private fun returnWz(wzTid: String) {
        val requestTagBeans = mutableListOf<RequestTagBean>()
        wzTid.split("|").forEach {
            requestTagBeans.add(RequestTagBean(it))
        }
        if (SetInfo.isOffline()) {
            val offlineRequestDTO = OfflineRequestDTO()
            offlineRequestDTO.requestType = Constant.REQUEST_RETURN_WZ
            offlineRequestDTO.requestJson = mapOf(
                "reqId" to UUID.randomUUID().toString(),
                "deviceId" to DeviceUtils.getUniqueDeviceId(),
                "archiveInfos" to Gson().toJson(requestTagBeans),
//                "returnId" to (readerId ?: ""),
//                "returnBy" to (readerName ?: ""),
//                "remark" to reason,
            ).toString()
            offlineRequestDTO.requestTime = System.currentTimeMillis()
            GreenDaoManager.addOfflineRequestDTO(offlineRequestDTO)
            toast("归还成功")
            LogUtils.e("离线归还成功")
            onBackPressed()
        } else {
            launch({
                val rp = getApiService().inboundSaveInfo(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        "archiveInfos" to requestTagBeans,
//                        "returnId" to (readerId ?: ""),
//                        "returnBy" to (readerName ?: ""),
//                        "remark" to reason,
                    )
                ).dataConvert()
                if (rp.result > 0) {
                    toast("归还成功")
                    onBackPressed()
                } else {
                    toast(rp.msg)
                }
            }, {
                toast(it.message)
            })
        }
    }

    private fun borrowWz(wzTid: String) {
        val requestTagBeans = mutableListOf<RequestTagBean>()
        wzTid.split("|").forEach {
            requestTagBeans.add(RequestTagBean(it))
        }
        if (SetInfo.isOffline()) {
            val offlineRequestDTO = OfflineRequestDTO()
            offlineRequestDTO.requestType = Constant.REQUEST_BORROW_WZ
            offlineRequestDTO.requestJson = mapOf(
                "reqId" to UUID.randomUUID().toString(),
                "deviceId" to DeviceUtils.getUniqueDeviceId(),
                "archiveInfos" to Gson().toJson(requestTagBeans),
                "borrowerId" to (readerId ?: ""),
                "borrowerBy" to (readerName ?: ""),
                "remark" to reason,
            ).toString()
            offlineRequestDTO.requestTime = System.currentTimeMillis()
            GreenDaoManager.addOfflineRequestDTO(offlineRequestDTO)
            toast("借阅成功")
            LogUtils.e("离线借阅成功")
            onBackPressed()
        } else {
            launch({
                //将wzTid.split("|") 新建成RequestTagBean对象列表
                val rp = getApiService().outboundSaveInfo(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        "archiveInfos" to requestTagBeans,
                        "borrowerId" to (readerId ?: ""),
                        "borrowerBy" to (readerName ?: ""),
                        "remark" to reason,
                    )
                ).dataConvert()
                if (rp.result > 0) {
                    toast("借阅成功")
                    onBackPressed()
                } else {
                    toast(rp.msg)
                }
            }, {
                toast(it.message)
            })
        }
    }

    //下架
    private fun downWz(wzTid: String) {
        val requestTagBeans = mutableListOf<RequestTagBean>()
        wzTid.split("|").forEach {
            requestTagBeans.add(RequestTagBean(it))
        }
        if (SetInfo.isOffline()) {
            val offlineRequestDTO = OfflineRequestDTO()
            offlineRequestDTO.requestType = Constant.REQUEST_DOWN_WZ
            offlineRequestDTO.requestJson = mapOf(
                "reqId" to UUID.randomUUID().toString(),
                "deviceId" to DeviceUtils.getUniqueDeviceId(),
                "archiveInfos" to Gson().toJson(requestTagBeans),
//                "caseCode" to caseInfo!!.caseCode,
            ).toString()
            offlineRequestDTO.requestTime = System.currentTimeMillis()
            GreenDaoManager.addOfflineRequestDTO(offlineRequestDTO)
            toast("下架成功")
            LogUtils.e("离线下架成功")
            onBackPressed()
        } else {
            launch({
                val emptyResponse = getApiService().offSaveInfo(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        "archiveInfos" to requestTagBeans,
//                        "caseCode" to caseInfo!!.caseCode,
                    )
                ).dataConvert()
                if (emptyResponse.result > 0) {
                    toast("下架成功")
                    onBackPressed()
                } else {
                    toast(emptyResponse.msg)
                }
            }, {
                toast(it.message)
            })
        }
    }

    //上架
    private fun upWz(wzTid: String) {
        val requestTagBeans = mutableListOf<RequestTagBean>()
        wzTid.split("|").forEach {
            requestTagBeans.add(RequestTagBean(it))
        }
        if (SetInfo.isOffline()) {
            val offlineRequestDTO = OfflineRequestDTO()
            offlineRequestDTO.requestType = Constant.REQUEST_UP_WZ
            offlineRequestDTO.requestJson = mapOf(
                "reqId" to UUID.randomUUID().toString(),
                "deviceId" to DeviceUtils.getUniqueDeviceId(),
                "archiveInfos" to Gson().toJson(requestTagBeans),
                "caseCode" to caseInfo!!.caseCode,
            ).toString()
            offlineRequestDTO.requestTime = System.currentTimeMillis()
            GreenDaoManager.addOfflineRequestDTO(offlineRequestDTO)
            toast("上架成功")
            LogUtils.e("离线上架成功")
            switchScan(true)
        } else {
            launch({
                val emptyResponse = getApiService().onSaveInfo(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        "archiveInfos" to requestTagBeans,
                        "caseCode" to caseInfo!!.caseCode,
                    )
                ).dataConvert()
                if (emptyResponse.result > 0) {
                    toast("上架成功")
                    switchScan(true)
                } else {
                    toast(emptyResponse.msg)
                }
            }, {
                toast(it.message)
            })
        }
    }

    override fun getMyTitle(): String {
        when (operateType?.type) {
            OperateType.OPERATE_TYPE_GUIDE.type -> {
                mBinding.tvInout.visibility = View.GONE
                return "上架指导"
            }

            OperateType.OPERATE_TYPE_PUT.type -> {
                mBinding.tvInout.text = "上架"
                return "档案上架"
            }

            OperateType.OPERATE_TYPE_TAKE.type -> {
                mBinding.tvInout.text = "下架"
                return "档案下架"
            }

            OperateType.OPERATE_TYPE_RETURN.type -> {
                mBinding.tvInout.text = "归还"
                return "档案归还"
            }

            OperateType.OPERATE_TYPE_BORROW.type -> {
                mBinding.tvInout.text = "借阅"
                return "档案借阅"
            }

            OperateType.OPERATE_TYPE_REVERSE.type -> {
                mBinding.tvInout.text = "倒架"
                return "档案倒架"
            }
        }
        return "上架指导"
    }


    override fun onLeftClick() {
        if (isScanCaseReverse) {
            ReaderUtils.instance.stopScan()
            isScanCaseReverse = false
            mBinding.llScan.visibility = View.GONE
            mBinding.llFiles.visibility = View.VISIBLE
            ReaderUtils.instance.setPower(SetInfo.getScanWzPower())
            mBinding.tvCaseNumCn.text = caseInfo?.caseCodeTrans
            mBinding.tvRfid.visibility = View.GONE
        } else {
            onBackPressed()
        }
    }

    override fun onRightClick() {
        if (ReaderUtils.instance.isScanningRFID.value == true) {
            toast("请先停止扫描")
            return
        }
        mBinding.etCaseCode.setText("")
        mBinding.tvCaseTrans.text = ""
        mBinding.tvGuan.text = ""
        mBinding.tvKufang.text = ""
        mBinding.tvQu.text = ""
        mBinding.tvLie.text = ""
        mBinding.tvMian.text = ""
        mBinding.tvJie.text = ""
        mBinding.tvCeng.text = ""
        mBinding.tvConfirmCase.clickWithTrigger {
        }
        filesList.clear()
        filesAdapter.notifyDataSetChanged()
        ReaderUtils.instance.resetData()
        mBinding.tvCount.text = "共读到档案：0本"
    }

    override fun isScan(): Boolean {
        return true
    }

    override fun onTmCodeRead(code: String) {
        if (caseCode.isEmpty() && operateType?.type != OperateType.OPERATE_TYPE_GUIDE.type
            && operateType?.type != OperateType.OPERATE_TYPE_TAKE.type
            && operateType?.type != OperateType.OPERATE_TYPE_BORROW.type && operateType?.type != OperateType.OPERATE_TYPE_RETURN.type
        ) {
            toast("请先确认层位")
        } else {
            searchWz(code, 1, true)
        }
    }

    override fun onEpcRead(tagInfo: UHFTAGInfo) {
        super.onEpcRead(tagInfo)
        if (isScanCaseReverse) { //源层位扫描时
            searchCase(tagInfo.tid)
            return
        }
        if (caseCode.isEmpty() && operateType?.type != OperateType.OPERATE_TYPE_GUIDE.type
            && operateType?.type != OperateType.OPERATE_TYPE_TAKE.type
            && operateType?.type != OperateType.OPERATE_TYPE_BORROW.type && operateType?.type != OperateType.OPERATE_TYPE_RETURN.type
        ) {
            searchCase(tagInfo.tid)
        } else {
            searchWz(tagInfo.tid, 0)
        }
    }

    private fun searchWz(code: String, nType: Int, needTips: Boolean = false) {
        if (SetInfo.isOffline()) {
            GreenDaoManager.findFilesInfoDTO(code)?.let {
                if (!it.caseCodeTrans.isNullOrEmpty()
                    && caseInfo != null
                    && caseInfo!!.caseCode != it.caseCode
                    && operateType?.type != OperateType.OPERATE_TYPE_REVERSE.type
                ) {
                    if (!it.caseCodeTrans.startsWith("错架")) {
                        it.caseCodeTrans =
                            "错架 " + it.caseCodeTrans
                    }
                } else {
                    if (it.caseCodeTrans.isNullOrEmpty() || !it.caseCodeTrans.startsWith("层架")) {
                        it.caseCodeTrans =
                            "层架 " + if (it.caseCodeTrans.isNullOrEmpty()) "未上架" else it.caseCodeTrans
                    }
                }
                //判断是否已存在 szWZID相等
                val index = filesList.indexOfFirst { wz ->
                    it.eid == wz.eid
                }
                if (index >= 0) {
                    toast("档案已存在，请检查数据")
                } else {
                    filesList.add(0, it)
                    filesAdapter.notifyDataSetChanged()
                    mBinding.tvCount.text = "共读到档案：${filesList.size}本"
                }
            } ?: run {
                LogUtils.e("离线模式：未找到该档案")
//                toast("未找到该档案")
            }
        } else {
            launch({
                LogUtils.e(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        "tagList" to listOf(RequestTagBean(code)),
                    ).toString()
                )

                val filesRp = getApiService().guidanceArchiveReq(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        "tagList" to listOf(RequestTagBean(code)),
                    )
                ).dataConvert()

                LogUtils.e("查询成功****" + "fff")
                if (filesRp.archiveInfo.isNullOrEmpty()) {
                    LogUtils.e("-->未找到该档案")
                    if (needTips) {
//                        toast("未找到该档案")
                    }
                    return@launch
                }
                if (operateType?.type == OperateType.OPERATE_TYPE_TAKE.type && filesRp.archiveInfo[0].borrowStatus == 2) {
                    LogUtils.e("***下架时 过滤未上架")
                    return@launch
                }
                if (!filesRp.archiveInfo[0].caseCodeTrans.isNullOrEmpty()
                    && caseInfo != null
                    && caseInfo!!.caseCode != filesRp.archiveInfo[0].caseCode
                    && operateType?.type != OperateType.OPERATE_TYPE_REVERSE.type
                ) {
                    filesRp.archiveInfo[0].caseCodeTrans =
                        "错架 " + filesRp.archiveInfo[0].caseCodeTrans
                } else {
                    if (filesRp.archiveInfo[0].caseCodeTrans.isNullOrEmpty() || !filesRp.archiveInfo[0].caseCodeTrans.startsWith("层架")) {
                        filesRp.archiveInfo[0].caseCodeTrans =
                            "层架 " + if (filesRp.archiveInfo[0].caseCodeTrans.isNullOrEmpty()) "未上架" else filesRp.archiveInfo[0].caseCodeTrans
                    }
                }
                //判断是否已存在 szWZID相等
                val index = filesList.indexOfFirst { it.eid == filesRp.archiveInfo[0].eid }
                if (index >= 0) {
                    toast("档案已存在，请检查数据")
                } else {
                    filesList.add(0, filesRp.archiveInfo[0])
                    filesAdapter.notifyDataSetChanged()
                    mBinding.tvCount.text = "共读到档案：${filesList.size}本"
                }
            }, {
                if (needTips) {
//                    toast("-未找到该档案")
                }
                LogUtils.e("-->未找到该档案")
            })
        }
    }

    private fun searchCase(tid: String, isCaseCode: Boolean = false) {
        if (SetInfo.isOffline()) {
            (if (isCaseCode) GreenDaoManager.findCaseCodeDTO4CaseCode(tid) else GreenDaoManager.findCaseCodeDTO(
                tid
            ))?.let {
                hideSoftKeyboard()
                //将it.szWZCaseNoTran按照01列A面01节01层格式分割出数据
                val caseNoList = it.caseCodeTrans.split("馆", "库房", "区", "列", "面", "节", "层")
                mBinding.etCaseCode.setText(it.caseCode)
                mBinding.tvCaseTrans.text = it.caseCodeTrans

//                mBinding.tvGuan.text = caseNoList[0] ?: ""
//                mBinding.tvKufang.text = caseNoList[1] ?: ""
//                mBinding.tvQu.text = caseNoList[2] ?: ""
//                mBinding.tvLie.text = caseNoList[3] ?: ""
//                mBinding.tvMian.text = caseNoList[4] ?: ""
//                mBinding.tvJie.text = caseNoList[5] ?: ""
//                mBinding.tvCeng.text = caseNoList[6] ?: ""
                mBinding.tvConfirmCase.clickWithTrigger { view ->
                    if (isScanCaseReverse) {
                        allCaseReverse(it.caseCode, it.caseCodeTrans)
                    } else {
                        getCaseCodeSuccess(it)
                    }
                }
                mBinding.tvConfirmCase.performClick()
            } ?: run {
                LogUtils.e("离线模式：未找到该层位")
                toast("层位不存在，请检查")
            }
        } else {
            launch({
                val caseRp = getApiService().onReqCaseCode(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        if (isCaseCode) {
                            "caseCode" to tid
                        } else {
                            "eid" to tid
                        }
                    )
                ).dataConvert()
                if (!caseRp.caseCodeTrans.isNullOrEmpty()) {
                    hideSoftKeyboard()
                    val caseNoList =
                        caseRp.caseCodeTrans.split("馆", "库房", "区", "列", "面", "节", "层")
                    mBinding.etCaseCode.setText(caseRp.caseCode)
                    mBinding.tvCaseTrans.text = caseRp.caseCodeTrans

//                    mBinding.tvGuan.text = caseNoList[0] ?: ""
//                    mBinding.tvKufang.text = caseNoList[1] ?: ""
//                    mBinding.tvQu.text = caseNoList[2] ?: ""
//                    mBinding.tvLie.text = caseNoList[3] ?: ""
//                    mBinding.tvMian.text = caseNoList[4] ?: ""
//                    mBinding.tvJie.text = caseNoList[5] ?: ""
//                    mBinding.tvCeng.text = caseNoList[6] ?: ""
                    mBinding.tvConfirmCase.clickWithTrigger { view ->
                        if (isScanCaseReverse) {
                            allCaseReverse(caseRp.caseCode, caseRp.caseCodeTrans)
                        } else {
                            getCaseCodeSuccess(caseRp)
                        }
                    }
                    mBinding.tvConfirmCase.performClick()
                }
            }, {
                LogUtils.file(tid + "--> 未找到该层位")
                toast("层位不存在，请检查")
            })
        }
    }

    private fun allCaseReverse(caseCode: String, caseCodeTrans: String) {
        ReaderUtils.instance.stopScan()
        launch({
            val caseRp = getApiService().checkCaseCheck(
                mapOf(
                    "reqId" to UUID.randomUUID().toString(),
                    "deviceId" to DeviceUtils.getUniqueDeviceId(),
                    "caseCode" to caseCode
                )
            ).dataConvert()
            isScanCaseReverse = false
            mBinding.llScan.visibility = View.GONE
            mBinding.llFiles.visibility = View.VISIBLE
            if (caseRp.archiveInfo != null && caseRp.archiveInfo.size > 0) {
                caseRp.archiveInfo.forEach {
                    if (it.borrowStatus == 4) {
                        it.caseCodeTrans = "外借 $caseCodeTrans"
                    } else {
                        it.caseCodeTrans = "层架 $caseCodeTrans"
                    }
                }
                //filesList添加caseRp.archiveInfo并去重
                filesList.forEach {
                    //将caseRp.archiveInfo中eid相等的去除
                    caseRp.archiveInfo.removeAll { archiveInfo ->
                        archiveInfo.eid == it.eid
                    }
                }
                filesList.addAll(caseRp.archiveInfo)
                filesAdapter.notifyDataSetChanged()
            }
            ReaderUtils.instance.setPower(SetInfo.getScanWzPower())
            mBinding.tvCount.text = "共读到档案：" + filesList.size + "本"

            mBinding.tvCaseNumCn.text = caseInfo?.caseCodeTrans
            mBinding.tvRfid.visibility = View.GONE
            if (operateType?.type == OperateType.OPERATE_TYPE_REVERSE.type) {
                mBinding.tvReverse.visibility = View.VISIBLE
            } else {
                mBinding.tvReverse.visibility = View.GONE
            }
        }, {
        })

    }

    private fun getCaseCodeSuccess(it: CaseCodeDTO) {
        caseCode = it.caseCodeTrans
        caseInfo = it
        mBinding.tvCaseNumCn.text = caseInfo?.caseCodeTrans
        ReaderUtils.instance.reset()
        switchScan(false)
    }

    private fun switchScan(isScan: Boolean) {
        if (isScan) {
            ReaderUtils.instance.reset()
            ReaderUtils.instance.setPower(SetInfo.getScanCasePower())
            caseCode = ""
            caseInfo = null
            mBinding.tvCaseNumCn.text = ""
            mBinding.etCaseCode.setText("")
            mBinding.tvCaseTrans.text = ""
            mBinding.tvGuan.text = ""
            mBinding.tvKufang.text = ""
            mBinding.tvQu.text = ""
            mBinding.tvLie.text = ""
            mBinding.tvMian.text = ""
            mBinding.tvJie.text = ""
            mBinding.tvCeng.text = ""
            mBinding.llScan.visibility = View.VISIBLE
            mBinding.llFiles.visibility = View.GONE
            mBinding.tvRfid.visibility = View.GONE
            mBinding.tvReverse.visibility = View.GONE
        } else {
            ReaderUtils.instance.setPower(SetInfo.getScanWzPower())
            filesList.clear()
            filesAdapter.notifyDataSetChanged()
            mBinding.tvCount.text = "共读到档案：0本"
            mBinding.llScan.visibility = View.GONE
            mBinding.llFiles.visibility = View.VISIBLE
            mBinding.tvRfid.visibility = View.GONE
            if (operateType?.type == OperateType.OPERATE_TYPE_REVERSE.type) {
                mBinding.tvReverse.visibility = View.VISIBLE
            } else {
                mBinding.tvReverse.visibility = View.GONE
            }
        }
    }

    private var isScanCaseReverse = false
    private fun switchCaseReverse() {
        isScanCaseReverse = true
        ReaderUtils.instance.reset()
        ReaderUtils.instance.setPower(SetInfo.getScanCasePower())
        mBinding.tvCaseNumCn.text = "源层架扫描"
        mBinding.etCaseCode.setText("")
        mBinding.tvCaseTrans.text = ""
        mBinding.tvGuan.text = ""
        mBinding.tvKufang.text = ""
        mBinding.tvQu.text = ""
        mBinding.tvLie.text = ""
        mBinding.tvMian.text = ""
        mBinding.tvJie.text = ""
        mBinding.tvCeng.text = ""
        mBinding.llScan.visibility = View.VISIBLE
        mBinding.llFiles.visibility = View.GONE
        mBinding.tvRfid.visibility = View.GONE
        mBinding.tvReverse.visibility = View.GONE
    }

    override fun listChange() {
        mBinding.tvCount.text = "共读到档案：${filesList.size}本"
    }

    override fun onBackPressed() {
        if (mBinding.llScan.visibility == View.VISIBLE
            || operateType?.type == OperateType.OPERATE_TYPE_GUIDE.type
            || operateType?.type == OperateType.OPERATE_TYPE_TAKE.type
            || operateType?.type == OperateType.OPERATE_TYPE_BORROW.type || operateType?.type == OperateType.OPERATE_TYPE_RETURN.type
        ) {
            super.onBackPressed()
        } else {
            switchScan(true)
        }
    }

}